﻿using System;
using System.IO;

namespace IcqSharp
{
    public class SNACHeader
    {
        public Boolean Valid = true;
        public UInt16 Family;
        public UInt16 Subtype;
        public UInt16 Flags;
        public UInt32 Ref;
        public UInt16 Version;

        public SNACHeader(MemoryStream stream)
        {
            // 10 bytes is the minimum size of a header
            if (stream.Available() < 10)
            {
                Valid = false; return;
            }

            // standard data
            Family = stream.ReadUInt16();
            Subtype = stream.ReadUInt16();
            Flags = stream.ReadUInt16();
            var Ref1 = stream.ReadUInt16();  // reference id (sequence)
            var Ref2 = stream.ReadUInt16();  // command
            Ref = (UInt32)Ref1 | ((UInt32)Ref2 << 0x10);

            // If flag bit 15 is set, we also have a version tag
            // (...at least that is what I think it is)
            if ((Flags & 0x8000) > 0)
            {
                // invalid TLV
                if (stream.Available() < 2)
                {
                    Valid = false; return;
                }

                var ExtraBytes = stream.ReadUInt16();

                // have no data
                if (stream.Available() < ExtraBytes)
                {
                    Valid = false; return;
                }

                if (ExtraBytes == 6)
                {
                    // read value (skip type and len)
                    stream.Seek(+4, SeekOrigin.Current);
                    Version = stream.ReadUInt16();
                }
                else if (ExtraBytes == 0x0E)
                {
                    // skip TLV(2) - unknown
                    stream.Seek(+8, SeekOrigin.Current);

                    // read value (skip type and len)
                    stream.Seek(+4, SeekOrigin.Current);
                    Version = stream.ReadUInt16();
                }
                else
                {
                    // skip unknown
                    stream.Seek(+ExtraBytes, SeekOrigin.Current);
                }
            }
        }


    }
}
